package com.zxl.yunpicture.infrastructure.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;

@Configuration
public class ThreadPoolExecutorConfig {

    private final ThreadPoolConfig properties;

    public ThreadPoolExecutorConfig(ThreadPoolConfig properties) {
        this.properties = properties;
    }

    @Bean("taskExecutor")
    public ThreadPoolExecutor threadPoolExecutor() {
        // 1. 任务队列（根据容量选择队列类型）
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(properties.getQueueCapacity());

        // 2. 线程工厂（自定义线程名前缀）
        ThreadFactory threadFactory = r -> {
            Thread thread = new Thread(r);
            thread.setName(properties.getThreadNamePrefix() + thread.getId());
            return thread;
        };

        // 3. 拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        // 4. 创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                properties.getCoreSize(),
                properties.getMaxSize(),
                properties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                workQueue,
                threadFactory,
                handler
        );

        // 5. 允许核心线程超时
        executor.allowCoreThreadTimeOut(properties.isAllowCoreThreadTimeout());

        return executor;
    }
}